package com.baichen;

import java.lang.reflect.Field;

public class LogHandler implements MyHandler{

    MyInterface myInterface;

    public LogHandler(MyInterface myInterface) {
        this.myInterface = myInterface;
    }

    @Override
    public String functionBody(String content) {
        StringBuilder sb = new StringBuilder();
        sb.append("System.out.println(\"before\");\n");
        sb.append("myInterface.").append(content).append("();\n");
        sb.append("System.out.println(\"after\");\n");
        return sb.toString();
    }

    @Override
    public void setMyInterface(MyInterface myInterfaceObject) throws NoSuchFieldException, IllegalAccessException {
        Class<? extends MyInterface> aClass = myInterfaceObject.getClass();
        Field myInterfaceField = aClass.getDeclaredField("myInterface");
        myInterfaceField.setAccessible(true);
        myInterfaceField.set(myInterfaceObject, myInterface);
    }
}
